import React, {FC, Key, useContext, useEffect, useMemo, useRef, useState} from 'react';
import "./index.less";
import {useRequest} from "ahooks";
import * as API from "@/services";
import {FrontJournalPeriod, queryMineFavColumns, queryMineFavColumnsByJournal} from "@/services";
import HxLineCollapse from "@/components/HxLineCollapse";
import {correspVal} from "@/utils/biz";
import {HxConfigContext} from "@/layouts/HxConfigContext";
import {Link} from "umi";
import {Empty, Input, message} from "antd";
import querystring from "query-string";
import {CloseOutlined} from "@ant-design/icons";

interface FavoriteColumnProps {
}

/**
 * 栏目收藏 页面
 */
const FavoriteColumn: FC<FavoriteColumnProps> = (props) => {
  const {isZhCN} = useContext(HxConfigContext)

  const activeKeyInitialized = useRef(false);
  const [activeKey, setActiveKey] = useState<Key[]>([])
  const [itemsMap, setItemsMap] = useState<Record<string, API.FrontJournalColumnCollection[]>>({})
  const [searchText, setSearchText] = useState("");

  const journalCollsReq = useRequest(() => API.queryMineFavColumnsByJournal({
    searchText
  }), {
    onSuccess: (resp) => {
      if (resp.flag) {
        setActiveKey([])
        setItemsMap({});
      }
    },
    refreshDeps: [searchText]
  });

  const journalColls = (journalCollsReq.data?.data || []).filter(t => !!t.journal?.id);

  useEffect(() => {
    const process = async () => {
      if (activeKey.length > 0) {
        for (const k of activeKey) {
          const items = itemsMap[`${k}`];
          if (!items) {
            const journalId = k as string;
            const resp = await API.queryMineFavColumns({
              journalId: journalId === "none" ? undefined : journalId,
              existJournalId: journalId === "none" ? false : undefined,
              pageSize: 1000,
              searchText: searchText,
            });
            itemsMap[`${journalId}`] = resp.data || [];
          }
          setItemsMap({...itemsMap})
        }
      }
    };
    process();
  }, [activeKey, searchText]);

  useEffect(() => {
    if (!activeKeyInitialized.current && activeKey.length === 0 && journalColls.length > 0) {
      const key = journalColls.map(journalColl => journalColl.journal?.id)
      setActiveKey(key)
      activeKeyInitialized.current = true;
    }
  }, [journalColls]);


  const collapseItems = useMemo(() => {
    return journalColls.map(journalColl => {
      const key = journalColl.journal?.id || "none";
      const items = itemsMap[`${key}`]
      const label = correspVal(isZhCN, journalColl?.journal?.journalNameCn, journalColl?.journal?.journalNameEn) || "其他";
      return {
        key: key,
        label: `${label} （${journalColl.total}）`,
        children: (
          <div className={"favorite-column-items"}>
            {items?.map(item => (
              <Link
                target={"_blank"}
                to={{
                  pathname: `/journal/${journalColl.journal?.id}/archive/column`,
                  search: querystring.stringify({columnId: item.journalColumn?.id}),
                }}
                key={`${key}_${item.id}`}
                className={"favorite-column-item"}
              >
                {item?.journalColumn?.name}
                <a className={"unfavorite-column-item-btn"} onClick={(e) => {
                  e.preventDefault();
                  e.stopPropagation();
                  API.fav("column", item!.journalColumn!.id, true, journalColl.journal?.id).then(resp => {
                    if (resp.flag) {
                      message.success("已取消收藏");
                      setItemsMap({
                        ...itemsMap,
                        [`${key}`]: items.filter(t => t.id !== item.id)
                      })
                    }
                  })
                }}>
                  <CloseOutlined/>
                </a>
              </Link>
            ))}
          </div>
        )
      }
    })
  }, [journalColls, itemsMap]);

  return (
    <div className={"favorite-column-container"}>
      <div className={"favorite-column-search-wrapper"}>
        <Input.Search
          placeholder="请输入关键词查找"
          enterButton={"搜索"}
          size={"large"}
          onSearch={(value) => {
            setSearchText(value);
          }}
        />
      </div>
      {
        collapseItems.length > 0 ? (
            <HxLineCollapse
              className={"fav-column-collapse"}
              activeKey={activeKey as string[]}
              onChange={setActiveKey}
              ghost
              items={collapseItems}/>
          ) :
          (
            <Empty/>
          )
      }

    </div>
  );
};

export default FavoriteColumn;
